//
//  WSMGoodNumCustomView.m
//  WinesMall
//
//  Created by Isaac on 17/9/18.
//  Copyright © 2017年 Isaac. All rights reserved.
//

#import "WSMGoodNumCustomView.h"

NSString * const ATableViewCellAEvent3 = @"minusEvent";
NSString * const ATableViewCellAEvent4 = @"addEvent";

@implementation WSMGoodNumCustomView


//- (instancetype)initWithFrame:(CGRect)frame {
//    if (self = [super initWithFrame:frame]) {
//        
//    }
//    return self;
//}

-(instancetype)initWithCoder:(NSCoder *)aDecoder {
    
    if (self = [super initWithCoder:aDecoder]) {
        UIView *view = [[[NSBundle mainBundle]loadNibNamed:@"WSMGoodNumCustomView" owner:self options:nil]objectAtIndex:0];
        [self addSubview:view];
        self.layer.borderWidth = 0.5;
        self.layer.borderColor = kLineColor.CGColor;
        _minusBtn.frame = CGRectMake(0, 0, 30, 30);
        _numberLabel.frame = CGRectMake(30, 0, 30, 30);
        _addBtn.frame = CGRectMake(60, 0, 30, 30);
        _numberLabel.layer.borderWidth = 0.5;
        _numberLabel.layer.borderColor = kLineColor.CGColor;
        
    }
    return self;
}
- (IBAction)handleMinus:(id)sender {
    if (_numberLabel.text.integerValue <= 1) {
        [_minusBtn setEnabled:NO];
    }
    [self routerEventWithName:ATableViewCellAEvent3 userInfo:@{@"title":@"minus", @"param":@"这是删减"}];

}
- (IBAction)handleAdd:(id)sender {
    if (_numberLabel.text.integerValue >= 0) {
        [_minusBtn setEnabled:YES];
    }
    [self routerEventWithName:ATableViewCellAEvent4 userInfo:@{@"title":@"add", @"param2":@"这是增加"}];

}

- (void)routerEventWithName:(NSString *)eventName userInfo:(NSDictionary *)userInfo {
    
    NSInvocation *invo = self.eventStrategy[eventName];
    [invo setArgument:&userInfo atIndex:2];
    [invo invoke];
    
    //需要继续往上传递：                    如果方法多的时候可以写在字典对应的每个方法里面来来决定单个方法是否要继承。
    //    [super routerEventWithName:eventName userInfo:userInfo];
    
}

- (void)aEvent:(NSDictionary *)userInfo {
//    NSLog(@"cell里面：   %@",userInfo);
    [super routerEventWithName:ATableViewCellAEvent3 userInfo:userInfo];

}
- (void)aEvent2:(NSDictionary *)userInfo {
//    NSLog(@"需要上传递cell里面2：   %@",userInfo);
    [super routerEventWithName:ATableViewCellAEvent4 userInfo:userInfo];
    
}


/**
 如果事件来源有多个，那就无法避免需要if-else语句来针对具体事件作相应的处理。这种情况下，会导致if-else语句极多。所以，可以考虑采用strategy模式来消除if-else语句。
 self.eventStrategy是一个字典，这个字典以eventName作key，对应的处理逻辑封装成NSInvocation来做value。
 在这种场合下使用Strategy模式，即可避免多事件处理场景下导致的冗长if-else语句。
 */
- (NSDictionary<NSString *, NSInvocation *> *)eventStrategy
{
    if (!_eventStrategy) {
        _eventStrategy = @{
                           ATableViewCellAEvent3: [self createInvocationWithSelector:@selector(aEvent:)],
                           ATableViewCellAEvent4: [self createInvocationWithSelector:@selector(aEvent2:)],
                           };
    }
    return _eventStrategy;
}

@end
